package com.example.demo.controller;

import com.example.demo.domain.Girl;
import com.example.demo.domain.Result;
import com.example.demo.respository.GirlRespository;
import com.example.demo.service.GirlService;
import com.example.demo.utils.ResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by wangbing on 2018/3/28.
 */
@RestController
public class GirlController {
    @Autowired
    private GirlRespository girlRespository;
    @Autowired
    private GirlService girlService;

    /**
     * 查询女生列表
     * @return
     */
    @GetMapping(value = "/girls")
    public List<Girl> girlList(){
        return girlRespository.findAll();

    }

    /**
     * 添加一个girl对象

     * @return
     */

    @PostMapping(value = "/girls")
    public Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult){
        Result result = new Result();
        if (bindingResult.hasErrors()){

            return ResultUtils.error(1,bindingResult.getFieldError().getDefaultMessage());
        }
        girl.setAge(girl.getAge());
        girl.setCupSize(girl.getCupSize());
        girl.setMoney(girl.getMoney());
        girlRespository.save(girl);

        return ResultUtils.success(girl);
    }
    /**
     *查询id
     */
    @GetMapping(value = "/girls/{id}")
    public Girl selectById(@PathVariable(value = "id") Integer id){
        return girlRespository.findOne(id);

    }

    /**
     * 根据id更新
     */
    @PutMapping(value = "/girls/{id}")
    public Girl girlUpdate(@PathVariable Integer id,
                            String cupSize,
                          Integer age,int money){
        Girl girl = new Girl();
        girl.setId(id);
        girl.setAge(age);
        girl.setCupSize(cupSize);
        girl.setMoney(money);
        return girlRespository.save(girl);


    }
    /**
     * 根据id删除
     */
    @DeleteMapping(value = "/girls/{id}")
public String girlDelete(@PathVariable(value = "id")Integer id){
         girlRespository.delete(id);
        return "del success!";
    }


    /**
     * 通过年龄查询
     */
    @GetMapping(value = "/girls/age/{age}")
    public List<Girl> girlListByAge(@PathVariable( "age")Integer age){

        return girlRespository.findByAge(age);
    }
//
    @PostMapping(value = "/girls/two")
    public void girlTwo(){
        girlService.insertTwo();

    }
@RequestMapping(value = "/getAge/grade")
    public void getAge(Integer id) throws Exception {
    girlService.getAge(id);

    }

}
